package com.lvmama.rhino.job;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvmama.rhino.mapper.ManGodCountMapper;
import com.lvmama.rhino.pojo.ManGodCount;
import com.lvmama.rhino.utils.CommonUtils;
import com.lvmama.rhino.utils.JedisTemplate;


/**
 * 2分钟执行一次,从redis中获取数据批量插入mysql
 * @author wuyunpeng
 *
 */
public class SaveBatchJob extends QuartzJobBean  {
	
	private JedisTemplate read = JedisTemplate.getReaderInstance();
	
	private JedisTemplate writer = JedisTemplate.getWriterInstance();
	
	private ObjectMapper mapper = new ObjectMapper();
	
	private Logger logger = Logger.getLogger(SaveBatchJob.class);

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		List<String> resultJsons = read.lrange(CommonUtils.KEY_FOR_MAN_GOD, 0, -1);
		if(CollectionUtils.isEmpty(resultJsons)){
			return ;
		}
		ApplicationContext applicationContext = (ApplicationContext) context.getJobDetail().getJobDataMap()
				.get("applicationContext");
		ManGodCountMapper manGodCountMapper = applicationContext.getBean(ManGodCountMapper.class);
		List<ManGodCount> manGodCounts;
		try {
			manGodCounts = mapper.readValue(resultJsons.toString(), mapper.getTypeFactory().constructCollectionType(List.class, ManGodCount.class));
			manGodCountMapper.saveBatch(manGodCounts);
			writer.del(CommonUtils.KEY_FOR_MAN_GOD);
			logger.info("sava batch for manGodCount success");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("sava batch for manGodCount failed");

		}
	}
	
	
}
